import re
import random
from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.core.mail import send_mail
from django_redis import get_redis_connection
from django.contrib.auth.hashers import make_password

from utils.verifyUtil import verifyParam
from utils.resFormatUtil import ResFormat
from ffmall.settings import EMAIL_HOST_USER
from celery_tasks.email.tasks import send_email_task
from apps.user.models import User

EMAIL_KEY = 'email:verification:%s'


# Create your views here.
# 邮箱验证码
class EmailVerificationView(View):
    DURATION = 3  # 有效时长，单位分钟

    @method_decorator(verifyParam('email'))
    def post(self, request):
        # 实现邮箱格式的验证
        email = request.POST.get('email')

        # 验证邮箱的格式
        re_email = r'(\w+)@(\w+)\.(\w+)'
        if not re.match(re_email, email):
            return ResFormat(status='PARAM_ERROR').json_response()

        # 校验发送验证码是够已经过去了60s
        cache_default = get_redis_connection()
        if cache_default.get(email):
            return ResFormat(status='ACCESS_RESTRICTION').json_response()

        verification_code = random.randint(100000, 999999)  # 6位随机验证码
        # 发送邮件
        # self.send_email_task(email, verification_code, self.DURATION)
        send_email_task.delay(email, verification_code, self.DURATION)

        # 'email:verification:%s' % email
        # return HttpResponse('test')
        return ResFormat().json_response()


# 注册
class RegisterView(View):
    @method_decorator(verifyParam('email', 'password', 'verify'))
    def post(self, request):
        """
        用户注册
        :param request:
        :return:
        """
        post = request.POST
        email = post.get('email')
        password = make_password(post.get('password'))
        verify = post.get('verify')

        # 验证邮箱的格式
        re_email = r'(\w+)@(\w+)\.(\w+)'
        if not re.match(re_email, email):
            return ResFormat(status='PARAM_ERROR').json_response()

        # 验证码校验
        cache = get_redis_connection(alias='verify_code')
        redis_verification = cache.get(EMAIL_KEY % email)

        if (not redis_verification) or (verify != redis_verification):  # 没有验证码或者是验证码和redis数据库中的验证码不一致
            return ResFormat(status='PARAM_ERROR').json_response()  # 返回参数错误

        # 及时释放存储空间
        cache.delete(EMAIL_KEY % email)
        # 邮箱是否注册
        user_query = User.objects.filter(email=email)
        if user_query:
            return ResFormat(status='ACCOUNT_REGISTRATION').json_response()  # 返回账户已注册

        # 保存用户信息
        User.objects.create(email=email, password=password)
        return ResFormat().json_response()